package com.example.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Value("${deepseek.api.key}")
    private String apiKey;

    private final String deepSeekApiUrl = "https://api.deepseek.com/chat/completions";

    // 使用 ConcurrentHashMap 来存储每个用户的对话历史
    private final Map<String, List<ChatMessage>> userChatHistory = new ConcurrentHashMap<>();

    // Jackson 的 ObjectMapper 用于 JSON 序列化
    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/message")
    public SseEmitter sendMessage(@RequestBody ChatRequest chatRequest, @RequestHeader("X-User-ID") String userId) {
        SseEmitter emitter = new SseEmitter(0L); // 0L 代表不超时
        new Thread(() -> {
            try {
                RestTemplate restTemplate = new RestTemplate();

                log.info("收到请求消息: {}", chatRequest.getMessage());

                // 获取或创建用户的对话历史
                List<ChatMessage> chatHistory = userChatHistory.computeIfAbsent(userId, k -> new ArrayList<>());
                log.info("为用户{}建立对话线程",userId);

                // 将用户的新消息添加到对话历史中
                chatHistory.add(new ChatMessage("user", chatRequest.getMessage()));

                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", "Bearer " + apiKey);
                headers.setContentType(MediaType.APPLICATION_JSON);

                // 构建请求体
                String requestBody = buildRequestBody(chatHistory);

                HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

                ResponseExtractor<Void> responseExtractor = response -> {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getBody()))) {
                        String line;
                        StringBuilder assistantResponse = new StringBuilder();
                        while ((line = reader.readLine()) != null) {
                            line = line.trim();
                            if (line.startsWith("data:")) {
                                String json = line.substring(5).trim(); // 去掉 "data: " 前缀
                                if (!json.isEmpty() && !json.equals("[DONE]")) {
                                    log.info("DeepSeek 流数据: {}", json);

                                    // 将完整的 API 响应传递给前端
                                    emitter.send(SseEmitter.event().data(json));

                                    // 解析 JSON 数据，提取 assistant 的回复内容
                                    if (json.contains("\"delta\":{\"content\":\"")) {
                                        String content = json.split("\"delta\":\\{\"content\":\"")[1]
                                                .split("\"")[0];
                                        assistantResponse.append(content);
                                    }
                                }
                            }
                        }

                        // 将 AI 的完整回复添加到对话历史中
                        if (assistantResponse.length() > 0) {
                            chatHistory.add(new ChatMessage("assistant", assistantResponse.toString()));
                        }

                        emitter.complete();
                    } catch (Exception e) {
                        log.error("读取流数据失败: {}", e.getMessage(), e);
                        emitter.completeWithError(e);
                    }
                    return null;
                };

                restTemplate.execute(deepSeekApiUrl, HttpMethod.POST, request -> {
                    request.getHeaders().addAll(headers);
                    request.getBody().write(requestBody.getBytes());
                }, responseExtractor);

            } catch (Exception e) {
                log.error("调用 DeepSeek API 失败: {}", e.getMessage(), e);
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }

    @PostMapping("/clear")
    public ResponseEntity<String> clearChatHistory(@RequestHeader("X-User-ID") String userId) {
        userChatHistory.remove(userId);
        log.info("用户{}数据已清空",userId);
        return ResponseEntity.ok("对话历史已清空");
    }

    // 使用 ObjectMapper 构建请求体，确保 JSON 格式正确
    private String buildRequestBody(List<ChatMessage> chatHistory) throws JsonProcessingException {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("model", "deepseek-chat");
        requestMap.put("messages", chatHistory);
        requestMap.put("stream", true);

        return objectMapper.writeValueAsString(requestMap);
    }

    public static class ChatRequest {
        private String message;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

    public static class ChatMessage {
        private String role;
        private String content;

        public ChatMessage(String role, String content) {
            this.role = role;
            this.content = content;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}